from .utils import Result
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import service.user as service
import service.post as post_service

router = APIRouter(prefix="/user")


class User(BaseModel):
    username: str = None
    password: str = None
    gender: int = None
    age: int = None
    email: str = None
    name: str = None


@router.get("/{username}", status_code=200)
async def get_user(username: str):
    user = service.get_user(username).todict()
    if user is None:
        return HTTPException(status_code=402, detail="User not found")
    return Result(message="Get user successfully", data=user, code=200)


@router.post("/login", status_code=200)
async def login(user: User):
    user_find = service.get_user(user.username)
    if user_find is None:
        raise HTTPException(status_code=401, detail="User not found")
    user_find = user_find.todict()
    if user_find['username'] == 'default':
        raise HTTPException(status_code=401, detail="Default")
    if user_find['password'] == user.password:
        return Result(message="Login successfully", data=user_find, code=200)
    else:
        raise HTTPException(status_code=401, detail="Password error")


@router.post("/register", status_code=200)
async def register(user: User):
    if service.create_user(user.username, user.password):
        return Result(message="Register successfully", code=201)
    else:
        raise HTTPException(status_code=410, detail="User already exists")


@router.put("/update", status_code=200)
async def user_update(user: User):
    if service.update_user(user.model_dump()):
        return Result(message="Update user successfully", code=202)
    else:
        raise HTTPException(detail="User not found", status_code=401)


@router.delete("/del/{username}", status_code=200)
async def user_delete(username: str):
    post_service.replace_username(username, 'default')
    if service.delete_user(username):
        return Result(message="Delete user successfully", code=204)
    else:
        raise HTTPException(detail="User not found", status_code=401)
